package com.platform.modules.sys.service.impl;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.utils.Constant;
import com.platform.common.utils.EncryUtils;
import com.platform.common.utils.HttpContextUtils;
import com.platform.common.utils.IpUtils;
import com.platform.common.utils.Query;
import com.platform.common.utils.ShiroUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.enumstatus.AptitudeEnum;
import com.platform.common.enumstatus.SystemEnum;
import com.platform.common.enumstatus.UserEnum;
import com.platform.modules.mail.service.MailService;
//import com.platform.modules.prj.entity.PrjPriceEntity;
//import com.platform.modules.prj.entity.PrjSelectionEntity;
//import com.platform.modules.prj.service.PrjSelectionService;
import com.platform.modules.sys.dao.SysOrgDao;
import com.platform.modules.sys.entity.SysAptitudeExtEntity;
import com.platform.modules.sys.entity.SysOrgAptitudeEntity;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysOrgUserEntity;
import com.platform.modules.sys.entity.SysRoleEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysAptitudeExtService;
import com.platform.modules.sys.service.SysDeptService;
import com.platform.modules.sys.service.SysOrgAptitudeService;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.modules.sys.service.SysOrgUserService;
import com.platform.modules.sys.service.SysRoleMenuService;
import com.platform.modules.sys.service.SysRoleOrgService;
import com.platform.modules.sys.service.SysRoleService;
import com.platform.modules.sys.service.SysUserRoleService;
import com.platform.modules.sys.service.SysUserService;

/**
 * 组织机构Service实现类
 *
 * @author 肖亮
 */
@Service("sysOrgService")
public class SysOrgServiceImpl extends ServiceImpl<SysOrgDao, SysOrgEntity> implements SysOrgService {
	@Autowired
	SysDeptService sysDeptService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private MailService mailService;
	//@Autowired
	//private PrjSelectionService prjSelectionService;
	@Autowired
	private SysOrgAptitudeService sysOrgAptitudeService;
	@Autowired
	private SysOrgUserService sysOrgUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysAptitudeExtService sysAptitudeExtService;
	@Value("${spring.mail.emailTile}")
	private String emailTile;
	
	@Value("${spring.mail.emailParameter}")
	private String emailParameter;
	
	@Value("${application.server.address}")
	private String address;
	
	@Value("${registUrl}")
	private String registUrl;
	
	
	
	@Override
	public IPage<SysOrgEntity> queryPage(Map<String, Object> params) {
		Page<SysOrgEntity> page = new Query<SysOrgEntity>(params).getPage();
		List<SysOrgEntity> orgList = baseMapper.selectList(page, params);
		return page.setRecords(orgList);
	}
	
	
	@Override
	public List<SysOrgEntity> queryList(Map<String, Object> params) {
		return baseMapper.selectList( params);
	}
	
	
	
	@Override
	public SysOrgEntity queryOne(Map<String, Object> params) {
		List<SysOrgEntity> list = baseMapper.selectList( params);
		if(list==null || list.isEmpty()) {
			return null;
		}else {
			assert list.size()>1 : "queryOne but " + list.size();
			return list.get(0);
		}
	}
	
	
	@Override
	public List<SysOrgEntity> queryAll(Map<String, Object> params) {
		return baseMapper.queryAll(params);
	}
	
	@Override
	public List<SysOrgEntity> queryOrgList(String userId){
		return baseMapper.queryOrgList(userId);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(SysOrgEntity sysOrg) {

//		String parentNo = sysOrg.getParentNo();

//		String maxId = baseMapper.queryMaxIdByParentNo(parentNo);
//		String orgNo = StringUtils.addOne(parentNo, maxId);
//		sysOrg.setOrgNo(orgNo);

//		int orgLevel = getOrgLevel(orgNo);
//		sysOrg.setOrgLevel(orgLevel);
		sysOrg.setCreateTime(new Date());
//		sysOrg.setOrgNo(orgNo);
		baseMapper.insert(sysOrg);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysOrgEntity sysOrg) {
		String orgNo = sysOrg.getOrgNo();
		int orgLevel = getOrgLevel(orgNo);
		sysOrg.setOrgLevel(orgLevel);

		String userName = sysOrg.getUserName();
		String password = sysOrg.getPassword();
        //用于修改企业账号密码
		SysUserEntity sysUserEntity = sysUserService.queryByUserName(userName);
		if(sysUserEntity != null){
			 // sha256加密
			if(password != null && !"".equals(password)){
				  String salt = sysUserEntity.getSalt();
			        sysUserEntity.setPassword(new Sha256Hash(password, salt).toHex());
			        sysUserEntity.setSalt(salt);
			}
	        sysUserService.updateById(sysUserEntity);
		}

		this.updateById(sysOrg);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String orgNo) {
		this.removeById(orgNo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(String[] orgNos) {
		this.removeByIds(Arrays.asList(orgNos));
	}
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String addOrg(SysOrgEntity sysOrg,SysUserEntity user,HttpServletRequest request) {
//		String localip = IpUtils.getIpAddr(request);	
		String orgNo = "";
		//获取当前电脑IP
//		String localip = "localhost";
//        try {
//            localip=InetAddress.getLocalHost().getHostAddress();
//            System.out.println("获取IP地址"+localip);
//		} catch (Exception e) {
//			
//		}

		String updateUserId = "";
		sysOrg.setCreateTime(new Date());
		sysOrg.setStatus(AptitudeEnum.aptitudeStatus.WBS.getKey());
		sysOrg.setCreateUserId("1");
		if(StringUtils.isBlank(sysOrg.getOrgNo())){
			super.save(sysOrg);
			sysDeptService.createRootDept(sysOrg.getOrgName(), sysOrg.getOrgNo());
		}else{
			super.updateById(sysOrg);
			updateUserId = sysOrg.getUserId();
			sysOrg.getIfUpdate();
		}
		      
		 //若人员机构保存成功走以下方法
		if(sysOrg != null &&  StringUtils.isNotBlank(sysOrg.getOrgNo())){
			orgNo = sysOrg.getOrgNo();
//			String orgNo = sysOrg.getOrgNo();                           //单位id
			String orgType = sysOrg.getOrgType();                       //单位类型
			String userName = sysOrg.getUserName();                     //用户登录名
			String orgName = sysOrg.getOrgName();                       //单位名称
			String password = sysOrg.getPassword();                     //用户登录密码
			String comartiphone = sysOrg.getComartiphone();             //法人手机号码
			String comartiCertCode = sysOrg.getComartiCertCode();       //法人身份证号码
			//生成验证标记
			String sign="";
			String uuid = UUID.randomUUID().toString().replaceAll("-",""); 
			if(uuid != null && !"".equals(uuid)){
				uuid = uuid.substring(0, 3);
				sign = userName+"_"+uuid;
			}
			SysUserEntity regUser = new SysUserEntity();
			regUser.setUserName(userName);
			String salt = RandomStringUtils.randomAlphanumeric(20);        //登录密码加密
			regUser.setPassword(new Sha256Hash(password, salt).toHex());   //登陆密码
			regUser.setSalt(salt);                                         //密码盐
			regUser.setGender("2");                                     
			regUser.setSignId(uuid);                                       //邮箱验证标记                                                            
		    regUser.setContact(comartiphone);                              //联系方式
		    regUser.setUserCard(comartiCertCode);                          //身份证号码
		    regUser.setRealName(orgName);                                  //登陆人员真实姓名
		    regUser.setStatus(AptitudeEnum.aptitudeStatus.WBS.getKey());   //审核中状态（注册完毕后默认）
		    regUser.setAccountType(SystemEnum.accountType.ORG.getKey());   //注册机构的人员账号类型默认为企业账号
		    regUser.setCreateTime(new Date());
		    regUser.setOrgNo(orgNo);
		    //保存人员
		    if(StringUtils.isNotBlank(updateUserId)){
		    	regUser.setUserId(updateUserId);
		    	sysUserService.updateById(regUser);
		    }else{
		    	sysUserService.save(regUser);
		    }
		    
		    //若人员保存成功走以下方法
		    if(regUser != null && StringUtils.isNotBlank(regUser.getUserId())){
		    	//保存角色
			    List<String> roleIdList = new ArrayList<String>();
				Map<String, Object> params = new HashMap<String, Object>();
				String roleCode = "";
				if("1".equals(orgType)){                     //建设单位
					roleCode = "JSDWGLY";
				}else if("2".equals(orgType)){               //勘察单位
					roleCode = "KCDWGLY";
				}else if("3".equals(orgType)){               //设计单位
					roleCode = "SJDWGLY";
				}else if("4".equals(orgType)){               //审图单位
					roleCode = "STJGGLY";
				}else if("5".equals(orgType)){               //监管单位
					roleCode = "JGDWGLY";//"JGDWDLY";
				}else if("6".equals(orgType)){               //运维单位
					roleCode = "YWDWGLY";
				}else if("7".equals(orgType)){               //勘察设计单位
					roleCode = "KCSJDWGLY"; //"KCSJDW";
				}else if("8".equals(orgType)){               //人防监管单位
					roleCode = "RFJGDWGLY"; //"RFJGDW";
				}else if("9".equals(orgType)){               //施工单位
					roleCode = "SGDWGLY";
				}else if("10".equals(orgType)){               //施工单位
					roleCode = "SGDWGLY";
				}else if("11".equals(orgType)){               //监理单位
					roleCode = "JLDWGLY";
				}
				
				params.put("roleCode", roleCode);
				List<String> roleList = sysRoleService.queryRoleIdList(params);
				
				if(roleList != null && roleList.size()>0){
					for(String sysRoleEntity:roleList){
						roleIdList.add(sysRoleEntity);
						
					}
				}

				//插入人员角色表
				regUser.setRoleIdList(roleIdList);
				String userId = regUser.getUserId();
				sysUserRoleService.saveOrUpdate(userId, roleIdList);
				
				// 发送邮箱
				this.sendEmail(sign,  sysOrg.getOrgNo(), sysOrg.getOrgLinkMailbox());
				
				/*/发送邮箱
			    String mailHtml=Constant.EMAIL_HTML_REG;
				mailHtml=mailHtml.replaceAll("\\{emailTile\\}", emailTile);
				mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+localip+":70"); 
				mailHtml=mailHtml.replaceAll("\\{emailParameter\\}", emailParameter);
				mailHtml=mailHtml.replaceAll("\\{orgNo\\}", sysOrg.getOrgNo()); 
				mailHtml=mailHtml.replaceAll("\\{orgLinkMailbox\\}", sysOrg.getOrgLinkMailbox()); 
			    String deSign = EncryUtils.encryption(sign); //翻译成密文
				mailHtml=mailHtml.replaceAll("\\{sign\\}", deSign);
				mailService.sendMail(sysOrg.getOrgLinkMailbox(), "系统用户注册验证邮件", mailHtml);*/
		    }
		}
		return orgNo;
	}
	
	
	
	
	
	private void sendEmail(String sign, String orgNo, String email) {
		String mailHtml=Constant.EMAIL_HTML_REG;
		mailHtml=mailHtml.replaceAll("\\{emailTile\\}", emailTile);
		mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+registUrl); 
		mailHtml=mailHtml.replaceAll("\\{emailParameter\\}", emailParameter);
		mailHtml=mailHtml.replaceAll("\\{orgNo\\}", orgNo); 
		mailHtml=mailHtml.replaceAll("\\{orgLinkMailbox\\}", email); 
	    String deSign = EncryUtils.encryption(sign); //翻译成密文
		mailHtml=mailHtml.replaceAll("\\{sign\\}", deSign);
		mailService.sendMail(email, "系统用户注册验证邮件", mailHtml);
	}
	
	
	
	
	
	
	
	
	/**
	 * 注册单位     
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendEmailBoxAgain(String userName,String orgLinkMailbox) {
		//获取当前电脑IP
		String localip = "localhost";
        try {
        	 InetAddress ia=null;
			     ia=ia.getLocalHost();
	            localip=ia.getHostAddress();
	            System.out.println("获取IP地址"+localip);
		} catch (Exception e) {
			// TODO: handle exception
		}
        String orgNo = "";
        String signId = "";
        Map<String, Object> params = new HashMap<String, Object>();
        	params.put("userName", userName);
        List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(params);
        if(orgUserList != null && orgUserList.size()>0){
        	orgNo = orgUserList.get(0).getOrgNo();
        	signId = orgUserList.get(0).getSignId();
        }
        
		String	sign = userName+"_"+signId;
		String deSign = EncryUtils.encryption(sign); //翻译成密文
		String mailHtml=Constant.EMAIL_HTML_REG;
		mailHtml=mailHtml.replaceAll("\\{emailTile\\}", emailTile);
		mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+registUrl); 
		mailHtml=mailHtml.replaceAll("\\{emailParameter\\}", emailParameter);
		mailHtml=mailHtml.replaceAll("\\{orgNo\\}", orgNo);
		mailHtml=mailHtml.replaceAll("\\{orgLinkMailbox\\}", orgLinkMailbox); 
//		String deSign = EncryUtils.encryption(sign); //翻译成密文
		mailHtml=mailHtml.replaceAll("\\{sign\\}", deSign);
		mailService.sendMail(orgLinkMailbox, "系统用户注册验证邮件", mailHtml);

	}

	@Override
	public List<SysOrgEntity> queryListByOrgNo(String orgNo) {
		return baseMapper.selectChildrensByOrgNo(orgNo);
	}

	private int getOrgLevel(String orgNo) {
		int two = 2;
		int four = 4;
		int six = 6;
		int egight = 8;
		int ten = 10;
		int level = 0;

		if (orgNo.length() == two) {
			level = 1;
		} else if (orgNo.length() == four) {
			level = 2;
		} else if (orgNo.length() == six) {
			level = 3;
		} else if (orgNo.length() == egight) {
			level = 4;
		} else if (orgNo.length() == ten) {
			level = 5;
		}

		return level;
	}

	
	
	
	/**
	 * 查询资质机构
	 */
	@Override
	public List<SysOrgEntity> AptitudeOrg(Map<String, Object> params) {
		return baseMapper.selectList(null,params);
	}
	
	
	/**
	 * 查询资质机构Id
	 * orgType 企业类型（1.建设单位2.勘察单位3.设计单位4.审图办单位5.监管机构单位6.运维单位7.勘察设计）
	 */
	@Override
	public List<String> AptitudeOrgNo() {
		
		Map<String, Object> params = new HashMap<String, Object>();
		List<String> orgNoList = new ArrayList<String>();
		    params.put("orgType", SystemEnum.orgType.STDW.getKey());
			params.put("aptitudeStatus", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
			params.put("status", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
		List<SysOrgEntity> orgList = baseMapper.selectList(null,params);

	    if(orgList !=null && orgList.size()>0 && orgList.size()<=3){
	    	for(SysOrgEntity sysOrgEntity:orgList){
		    		orgNoList.add(sysOrgEntity.getOrgNo());
	    	}
	    }else if(orgList !=null && orgList.size()>3){
	    	for(int i=0;i<=3;i++){
	    		orgNoList.add(orgList.get(i).getOrgNo());
	    	}
	    }
		
		return orgNoList;
	}



}
